#include "us_delay.h"

static TIM_HandleTypeDef htim3;

void TIM3_Init(void) {
  __HAL_RCC_TIM3_CLK_ENABLE();

  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 84 - 1;  // Prescaler to get 1 MHz timer clock (assuming 84 MHz APB1 clock)
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 0xFFFFFFFF;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  HAL_TIM_Base_Init(&htim3);
  HAL_TIM_Base_Start(&htim3);
}

void delay_us(uint32_t us) {
  __HAL_TIM_SET_COUNTER(&htim3, 0);  // Reset the counter
  while (__HAL_TIM_GET_COUNTER(&htim3) < us);  // Wait until the counter reaches the us value
}

